import requests
import json
from datetime import datetime
from distutils.util import strtobool
from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger
from common.notice_tools import NoticeTools
from common.welab_k8s.k8s_pod import K8sPod
from common.welab_k8s import init_k8s
from app.notice_center.models.nc_n9e_alarm_record import NCN9eAlarmRecord
from app.notice_center.handlers.nc_n9e_alarm_handler import NCN9eAlarmHandler
from setting import config



class NCN9eCallbackPodHealHandler():
    """  Self Healing Handler
    """
    def __init__(self):
        init_k8s()
        self.token = config.FSR_POD_RESTART_TOKEN
        self.k8s_pod = K8sPod()
        self.notice_tools = NoticeTools()



    def filter_alarm_info(self, data: dict):
        alarm_data = {
            "status": "resolved" if data["is_recovered"] else "firing",
            "namespace": "",
            "pod": ""
        }
        
        for tag in data["tags"]:
            if tag.startswith("namespace="):
                alarm_data["namespace"] = tag.split("namespace=")[1]
                
            if tag.startswith("pod="):
                alarm_data["pod"] = tag.split("pod=")[1]
                
        return alarm_data


    def post_nc_n9e_heal_pod_restart(self, db: Session, data: dict, token: str):
        try:
            logger.info(f"pod restart 收到回调告警信息=>{data}")

            alarm_data = self.filter_alarm_info(data)

            # 前期数据判断
            if "" in list(alarm_data.values()):
                # token验证
                logger.error(f"pod restart: value is null")
                return False
            
            if self.token != token:
                logger.error(f"pod restart: token is error")
                return False
            
            if alarm_data["status"] == "resolved":
                logger.info(f"pod restart: status is resolved, nothing")
                return False
                                
            if alarm_data["namespace"] != "prod":
                logger.error(f"pod restart: namespace is not prod")
                return False
                    
            # 全局维护：不告警、不回调
            nc_n9e_alarm_handler = NCN9eAlarmHandler()
            global_record_info = NCN9eAlarmRecord.get_object_info_for_block_global(db)
            if global_record_info and not nc_n9e_alarm_handler.check_alert_notice_maintain(global_record_info):
                logger.info(f"container cpu usage: block alarm in global maintain")
                return True
                    
            # 处理pod异常的删除操作
            result = self.handle_pod_restart(db, alarm_data["namespace"], alarm_data["pod"])
            if not result:
                logger.error(f"handle pod restart failed")
                return False

            logger.info(f"handle pod restart success")
        except Exception as e:
            message = f"pod restart callback error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True



    def handle_pod_restart(self, db: Session, namespace: str, pod: str):
        """
        处理pod异常的删除操作
        """
        # 删除pod
        result = self.k8s_pod.delete_pod_from_namespace(namespace, pod)
        if not result:
            message = f"n9e故障自愈 => {pod}服务异常.已执行回调操作, 删除pod失败"
            logger.error(f"delete pod failed => {message}")
        else:
            message = f"n9e故障自愈 => {pod}服务异常.已执行回调操作, 删除pod成功"
            logger.info(f"delete pod success => {message}")

        # 发送处理结果信息到企业微信群
        self.notice_tools.send_wechat_group(message)
        


        return True


